package eva

import (
	"context"
	"trusteva/app/eva/internal/ruleutil"
	"trusteva/app/eva/model"

	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRuleLogic {
	return &DeleteRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteRuleLogic) DeleteRule(req *types.DeleteRuleRo) (resp *types.DeleteRuleRsp, err error) {
	var m model.Rule
	err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.Id).First(&m).Error
	if err != nil {
		return nil, err
	}
	err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.Id).
		Delete(&model.Rule{}).Error
	if err != nil {
		return nil, err
	}

	rules, _ := ruleutil.ParseRules(m)
	for _, v := range rules {
		_, err = l.svcCtx.RedisClient.SremCtx(l.ctx, v.Key())
		if err != nil {
			return nil, err
		}
	}

	return
}
